#!/bin/bash
# version: V1.0.0 -- 202111201634
longtime=$(date +%Y%m%d%H%M)
echo "[${longtime}] init mysqld autoStart start"
## 读取初始化变量
source init_variable
# 检查变量,写入默认值
source check_var
checkAndSetVar
# 获取系统信息
cd ../../os/
source ./os_release.sh
cd -
# 检查系统类型
check_systemctl_type

function systemd_insert() {
     # 替换模板,写入到临时配置文件
    printf "$(cat init_variable)\ncat << EOF\n$(cat mysqld.service.tpl)\nEOF"|bash > tmp/mysqld.service.tmp
    cp tmp/mysqld.service.tmp /etc/systemd/system/mysqld.service
    systemctl daemon-reload
    systemctl enable mysqld
    systemctl stop mysqld
    sleep 1
    systemctl start mysqld
    systemctl status mysqld
}


function chkconfig_insert() {
    if [ ! "$(command -v chkconfig)" ];then
            echo "[${longtime}]not found command chkconfig"
            exit 0
    fi
    cp ${basedir}/support-files/mysql.server /etc/init.d/mysqld
    sed -i "s:^basedir=.*$:basedir=${basedir}:g" /etc/init.d/mysqld
    sed -i "s:^datadir=.*$:datadir=${datadir}:g" /etc/init.d/mysqld
    sed -i "/Starting/a\    \$\{basedir\}/sh/mysql_reset.sh/" /etc/init.d/mysqld
    chmod +x /etc/init.d/mysqld
    chkconfig --add mysqld
    service mysqld stop
    sleep 1
    service mysqld start
}

# 检查创建临时文件夹
mkdir -p tmp

if [ ${SYSTEMCTL_TYPE} == 1 ];then
    if [ ! "$(command -v systemctl)" ];then
        echo "not found command systemctl so ..."
        chkconfig_insert
    else
        systemd_insert
    fi
elif [ ${SYSTEMCTL_TYPE} == 2 ]; then
    chkconfig_insert
else
  echo -e "\033[31m unrecognized this system \033[0m"
fi


echo "[${longtime}] init mysqld autoStart end"